<template>
	<div class="login">
		<div>
			<h2>请登录</h2>
		</div>
		<div class="lo">
			<el-form :model="user" ref="user" :rules="rules">
				<el-form-item label="用户号:" prop="username">
					<el-input prefix-icon="el-icon-user" class="d2" type="text" v-model="user.username"
						placeholder="请输入你的用户昵称"></el-input>
				</el-form-item>
				<el-form-item label="登录密码" prop="password" class="d3">
					<el-input prefix-icon="el-icon-lock" type="password" v-model="user.password"
						placeholder="请输入登录密码,5位纯数字"></el-input>
				</el-form-item>
				<el-form-item class="d4">
					<el-button type="primary" @click="login('user')">登录</el-button>
				</el-form-item>
			</el-form>
		</div>
	</div>
</template>

<script>
	export default {
		name: 'MobileLogin',
		data() {
			return {
				user: {
					// checked : false
				}, //登录用户信息
				rules: {
					username: [{ //账户验证
						required: true,
						message: '账号不能为空',
						trigger: 'blur',
					}],
					password: [{
						required: true,
						message: '密码不能为空',
						trigger: 'blur',
					}],
				}
			}
		},
		methods: {
			login(formName) {
				this.$refs[formName].validate((valid) => {
					if (valid) {
						this.$axios.post('/api/login', this.user, {
							headers: {
								'Content-Type': 'application/x-www-form-urlencoded;charset=utf8'
							}
						}, ).then((res) => {
							if (res.status == 200) {
								console.log(res);
								localStorage.setItem("token", res.data.data.token) //保存token
								this.$get('/api/user/info').then((res2) => {
									console.log(res2);
									if (res2.status == 200) {
										console.log(res2.data.data);
										localStorage.setItem('account', res2.data.data
											.account) //用户账号的名字
										localStorage.setItem('name', res2.data.data.name) //显示的名字
										localStorage.setItem('role', res2.data.data.role) //权限
										localStorage.setItem('img', res2.data.data.img) //图片
										let now = new Date();
										let loginTime = now.toLocaleString(); // 转换为本地时间字符串  
										localStorage.setItem('loginTime',
											loginTime); // 存储到localStorage中
										this.$message({
											message: "登录成功",
											type: "success"
										})
										if (res2.data.data.role == 'adm') {
											this.$router.push('/home/administrator');
										}
										if (res2.data.data.role == 'usr') {
											this.$router.push('/moblie/home');
										}
									}
								}).catch((error1) => {
									console.log(error1);
								})
							}
						}).catch((error2) => {
							console.log(error2);
						})
					}
				})
			},
		},
		mounted() {
			localStorage.setItem("token", '') //登录前先自定一个空的token
		}
	}
</script>

<style scoped>
	.login {
		width: 100%;
		height: 100%;
		margin: auto;
		background-color: cornflowerblue;
	}
</style>